package com.kaikeba.controller;

import com.kaikeba.entity.User;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/consumer")
@Slf4j
@DefaultProperties(defaultFallback = "defaultFallBack")  //指定全局降级方法
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/{id}")
    //@HystrixCommand(fallbackMethod = "fallBack" )  //声明一个降级逻辑方法
    @HystrixCommand
    public String queryById(@PathVariable long id){
        String url = "HTTP://user-service/user/"+id;

//        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
//        ServiceInstance serviceInstance = instances.get(0);
//        url = "http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/user/"+id;
        String object = restTemplate.getForObject(url, String.class);
        System.out.println(object);

        if (object==null){
            throw new RuntimeException("error");
        }
        return object;
    }


 /*   public String fallBack(long id){
        log.error("查询用户信息失败。");
        return "对不起，网络太拥挤了！";
    }
*/

    public String defaultFallBack(){
        return "默认提示：对不起，网络太拥挤了！";
    }


}
